<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\StoreTeamActivity;
use App\TeamActivity;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TeamActivityController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : 'order';
        $orderType = $request->order_type ? $request->order_type : 'asc';
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = TeamActivity::orderBy($orderBy, $orderType)->whereHas('goods')->with(['goods.specPrices']);
        return $lists->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreTeamActivity $request)
    {
        if (TeamActivity::where('goods_id', $request->goods_id)->first()) {
            return response(['message' => '该商品已参与拼团活动，请勿重复发起'], 400);
        }
        TeamActivity::create($request->all());
        return response(['message' => '创建成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\TeamActivity $teamActivity
     * @return \Illuminate\Http\Response
     */
    public function show(TeamActivity $teamActivity)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\TeamActivity $teamActivity
     * @return \Illuminate\Http\Response
     */
    public function edit(TeamActivity $teamActivity)
    {
        //
    }

    /**
     * @param StoreTeamActivity $request
     * @param TeamActivity $teamActivity
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(StoreTeamActivity $request, TeamActivity $teamActivity)
    {
        if ($teamActivity->goods_id != $request->goods_id
            && TeamActivity::where('goods_id', $request->goods_id)->first()) {
            return response(['message' => '该商品已参与拼团活动，请勿重复发起'], 400);
        }
        $teamActivity->update($request->all());
        return response(['message' => '修改成功']);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\TeamActivity $teamActivity
     * @return \Illuminate\Http\Response
     */
    public function destroy(TeamActivity $teamActivity)
    {
        //todo
        $teamActivity->delete();
        return response(['message' => '删除成功']);
    }
}
